import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.EventTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.assigners.ProcessingTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

import java.time.Duration;

public class TimeWindow_Session_AggFun {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
//        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());
        env.setParallelism(1);

        //2.从端口获取数据
        DataStreamSource<String> streamSource = env.socketTextStream("localhost", 9999);

        //3.把数据转为JSON字符串
        SingleOutputStreamOperator<WaterSensor> waterSensorJsonStream = streamSource.map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String value) throws Exception {
//                System.out.println("数据进来的时间："+System.currentTimeMillis()/1000);
                String[] split = value.split(",");
                WaterSensor waterSensor = new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
                return waterSensor;
            }
        })
                .assignTimestampsAndWatermarks(WatermarkStrategy
                        .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                .withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
                    @Override
                    public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                        return element.getTs()*1000;
                    }
                })
                )

                ;
        //4.将相同的id聚合到一块
        KeyedStream<WaterSensor, Tuple> keyedStream = waterSensorJsonStream.keyBy("id");

        //5.开启一个基于处理时间的滚动窗口 因为是在keyby之后开的窗，所以窗口是分key的
        WindowedStream<WaterSensor, Tuple, TimeWindow> window = keyedStream.window(EventTimeSessionWindows.withGap(Time.seconds(3)));

        //TODO 6.对窗口中的数据做Sum累加计算用AggFun实现
        window.aggregate(new AggregateFunction<WaterSensor, Integer, Integer>() {
            //创建累加器 每个窗口创建一个累加器
            @Override
            public Integer createAccumulator() {
                System.out.println("创建累加器。。。");
                return 0;
            }

            //累加操作
            @Override
            public Integer add(WaterSensor value, Integer accumulator) {
                System.out.println("累加操作。。。");
                return value.getVc() + accumulator;
            }

            //通过累加器获取结果
            @Override
            public Integer getResult(Integer accumulator) {
                System.out.println("获取结果。。。");
                return accumulator;
            }

            //合并累加器  主要用于窗口合并的时候调用合并累加器 主要用于会话窗口
            @Override
            public Integer merge(Integer a, Integer b) {
                System.out.println("合并累加器。。。");
                return a + b;
            }
        }).print();

        env.execute();


    }
}
